import mysql.connector

class Database:
    def __init__(self):
        self.connection = mysql.connector.connect(
            host='localhost',
            user='root',
            password='123456',
            database='students_mistake',
            auth_plugin ='mysql_native_password'
        )
        self.cursor = self.connection.cursor()

    def insert_user(self, user):
        query = "INSERT INTO user (username, id, grade) VALUES (%s, %s, %s)"
        user_data = (user.username, user.userid, user.grade)
        self.cursor.execute(query, user_data)
        self.connection.commit()

    def insert_mistake_details(self, mistake_details):
        query = "INSERT INTO mistake_details (id, uid, type, details,latestDate,times,weight) VALUES (%s, %s, %s, %s,%s,%s,%s)"
        mistake_details_data = (mistake_details.id,mistake_details.uid, mistake_details.type, mistake_details.details, mistake_details.latestDate, mistake_details.times, mistake_details.weight)
        self.cursor.execute(query, mistake_details_data)
        self.connection.commit()

    def insert_mistake_history(self, mistake_history):
        query = "INSERT INTO mistake_history (id, uid, type, details, time, reason) VALUES (%s,%s, %s, %s,%s,%s)"
        mistake_history_data = (mistake_history.id,mistake_history.uid, mistake_history.type, mistake_history.details, mistake_history.time, mistake_history.reason)
        self.cursor.execute(query, mistake_history_data)
        self.connection.commit()

    def get_mistake_details_by_uid_type_details(self, uid, type, details):
        query = "SELECT id, latestDate, times, weight FROM mistake_details WHERE uid = %s and type = %s and details = %s"
        self.cursor.execute(query, (uid,type,details,))
        return self.cursor.fetchall()

    def update_mistake_details(self,weight_plus,isPlusTimes, uid,id,latestDate):
        query = "UPDATE mistake_details SET weight = weight+ %s, times = times + %s ,latestDate = %s WHERE uid = %s and id = %s"
        updated_data = (weight_plus,isPlusTimes,latestDate, uid,id)
        self.cursor.execute(query, updated_data)
        self.connection.commit()

    def get_all_mistake_details_by_uid(self,uid):
        query = "SELECT id, uid, type, details,latestDate, times, weight FROM mistake_details WHERE uid = %s"
        self.cursor.execute(query,(uid,))
        return self.cursor.fetchall()

    def close_connection(self):
        self.cursor.close()
        self.connection.close()